package main

import (
	"flag"
	"fmt"
	"github.com/hukn/gokit/util"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"

	httptransport "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"github.com/hukn/gokit/Service"
)

func main() {
	name := flag.String("name", "", "服务名")
	port := flag.Int("p", 0, "端口")
	flag.Parse()
	if *name == "" {
		log.Fatal("请指定服务名")
	}
	if *port == 0 {
		log.Fatal("请指定端口")
	}
	util.SetServiceNameAndPort(*name, *port)
	user := Service.UserService{}
	endpoint := Service.GenUserEndpoint(user)
	serverHandler := httptransport.NewServer(endpoint, Service.DecodeUserRequest, Service.EncodeUserResponse)
	r := mux.NewRouter()
	{
		r.Methods("GET", "DELETE").Path("/user/{uid:\\d+}").Handler(serverHandler)
		r.HandleFunc("/health", func(writer http.ResponseWriter, request *http.Request) {
			writer.Header().Set("Content-type", "application/json")
			writer.Write([]byte(`{"status":"ok"}`))
		})
	}
	//r.Handle("/user/{uid:\\d+}", serverHandler)
	errChan := make(chan error)
	go func() {
		util.RegService()
		err := http.ListenAndServe(":"+strconv.Itoa(*port), r)
		if err != nil {
			log.Println(err)
			errChan <- err
		}
	}()
	go func() {
		sig_c := make(chan os.Signal)
		signal.Notify(sig_c, syscall.SIGINT, syscall.SIGTERM)
		errChan <- fmt.Errorf("%s", <-sig_c)
	}()
	getErr := <-errChan
	util.DeRegService()
	log.Println(getErr)
}
